package com.qcby.admin.controller;


import com.qcby.admin.form.LinkAddForm;
import com.qcby.admin.form.LinkEditForm;
import com.qcby.admin.form.LinkPageForm;
import com.qcby.admin.model.SgLink;
import com.qcby.admin.service.SgLinkService;
import com.qcby.admin.utils.AliOSSUtils;
import com.qcby.admin.vo.LinkPageVo;
import com.qcby.framwork.utils.ResponseResult;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;

/**
 * <p>
 * 友链 前端控制器
 * </p>
 *
 * @author YYL
 * @since 2024-09-23
 */
@RestController
@RequestMapping("/content/link")
public class SgLinkController {
    @Autowired
    private SgLinkService linkService;
    @Autowired
    private AliOSSUtils aliOSSUtils;

    @GetMapping("/list")
    public ResponseResult list(LinkPageForm linkPageForm){
        LinkPageVo linkPageVo=linkService.linkList(linkPageForm);
        return ResponseResult.okResult(linkPageVo);
    }


    //文件直接上传到阿里云
    @PostMapping("/upload")
    public ResponseResult upload(MultipartFile file) throws IOException {
        //把图片上传到阿里oss服务中
        String url=aliOSSUtils.upload(file);
        return ResponseResult.okResult(url);
    }

    /*新增友链*/
    @PostMapping
    public ResponseResult add(@RequestBody LinkAddForm linkAddForm){
        // 从前端提交的数据中获取 logo 地址
        String logoUrl = linkAddForm.getLogo();
        //把图片上传到阿里oss服务中
        SgLink link=new SgLink();
        BeanUtils.copyProperties(linkAddForm,link);
        link.setLogo(logoUrl);
        link.setCreateTime(LocalDateTime.now());
        Boolean save=linkService.save(link);
        if(!save) return ResponseResult.errorResult(500,"新增友链失败");
        return ResponseResult.okResult();
    }

    /*根据ID回显友链*/
    @GetMapping("/{id}")
    public ResponseResult info(@PathVariable Long id){
        return ResponseResult.okResult(linkService.getById(id));
    }

    /*修改友链*/
    @PutMapping
    public ResponseResult edit(@RequestBody LinkEditForm linkEditForm){
        SgLink link=new SgLink();
        BeanUtils.copyProperties(linkEditForm,link);
        Boolean edit=linkService.updateById(link);
        if(!edit) return ResponseResult.errorResult(500,"修改友链失败");
        return ResponseResult.okResult();
    }

    /*删除友链*/
    @DeleteMapping("/{id}")
    public ResponseResult delete(@PathVariable Long id){
        boolean del=linkService.removeById(id);
        if(!del) return ResponseResult.errorResult(500,"删除友链失败");
        return ResponseResult.okResult();

    }
}

